<template>
  <view class="detail">
    <view class="address">
      <view class="title">配送地址</view>
      <view class="a-left">
        <view class="a-add">{{
          deliveryInfo.deliveryAddressProvinceName +
            deliveryInfo.deliveryAddressCityName +
            deliveryInfo.deliveryAddressAreaName +
            deliveryInfo.deliveryAddress || ''
        }}</view>
        <view class="a-name"
          >{{ deliveryInfo.deliveryReceipientName || '' }} {{ deliveryInfo.deliveryReceipientContact || '' }}</view
        >
      </view>
    </view>

    <view class="time">
      <view class="t-info">
        <view class="t-title">预计送达时间</view
        ><text style="color: #f25559">
          {{ orderData.deliveryTime || '' }}
        </text>
      </view>
      <text v-if="orderData.deliveryInfo.expressKind" class="t-way" style="margin-right: 44rpx">{{
        orderData.deliveryInfo.expressKind
      }}</text>
    </view>
    <view class="order clearfix">
      <view class="o-title">药品清单</view>
      <view v-for="(item, index) in orderData.drugs" :key="index" class="drug-list">
        <image class="drug-img" mode="aspectFit" :src="item.outerPackagePicUrl" />
        <view class="drug-info">
          <view v-if="item.productName" class="title">{{ item.commonName }} ({{ item.productName }})</view>
          <view v-else class="title">{{ item.commonName }}</view>
          <view class="drug-num">
            <view class="drug-n-money">
              <view class="spe">
                {{ item.preparationUnit }}*{{ item.packageSize }}{{ item.minimumUnit }}/{{ item.packageUnit }}
              </view>
              <view>￥{{ fix2Num(item.priceCent) }}</view>
            </view>
            <view class="drug-amount">x{{ item.amount }}</view>
          </view>
        </view>
      </view>
      <view class="drug-total">共{{ totalDrugs }}件，合计￥{{ totalMoney }}</view>

      <view
        v-if="!orderData.isPay && orderData.status !== 99 && orderData.status !== 98"
        class="drug-payment"
        @click="payment"
      >
        支 付
      </view>
    </view>
    <view class="sys">
      <view class="s-title">系统信息</view>
      <view class="s-item">
        <view class="s-i-left">需求编号</view>
        <view class="s-i-right">{{ orderData.orderNo }}</view>
      </view>
      <view class="s-item">
        <view class="s-i-left">创建时间</view>
        <view class="s-i-right">{{ orderData.createDate }}</view>
      </view>
      <view class="s-item">
        <view class="s-i-left">送达时间</view>
        <view class="s-i-right">{{ orderData.receivingDate || '' }}</view>
      </view>
    </view>
  </view>
</template>

<script>
import { getDrugOrderDetail, orderPay } from '@/api/drugInfo';
import { memberId } from '@/common/baseUrl';

export default {
  data() {
    return {
      patientId: '',
      orderId: '',
      orderData: {},
      deliveryInfo: {}
    };
  },

  onLoad(opt) {
    this.patientId = opt.patientId;
    this.orderId = opt.orderId;

    // this.patientId = 'e58be458118046bdbb17d43a4f5aab6a';
    // this.orderId = 'c01f4a8fad80473e98b6c53745141732';

    this.init();
  },

  onShow() {
    uni.$on('addressChange', (res) => {
      this.getAddress();
    });
  },

  onUnload() {
    uni.$off('addressChange');
  },

  computed: {
    totalDrugs() {
      let drugsNum = 0;
      this.orderData.drugs &&
        this.orderData.drugs.forEach((item) => {
          drugsNum += item.amount;
        });
      return drugsNum;
    },
    totalMoney() {
      return ((this.orderData.amount + this.orderData.freight) / 100 || 0).toFixed(2);
    }
  },
  methods: {
    async init() {
      getDrugOrderDetail(this.patientId, this.orderId).then((res) => {
        if (res.code !== 0) {
          uni.showModal({
            title: '错误',
            content: '获取订单详情失败'
          });
        } else {
          this.orderData = res.data;
          console.log(this.orderData);
          this.deliveryInfo = this.orderData.deliveryInfo;
        }
      });
    },
    fix2Num(num) {
      num = num || 0;
      return (num / 100).toFixed(2);
    },

    // 支付
    async payment() {
      const self = this;
      uni.showLoading({
        title: '加载中',
        mask: true
      });
      const payParams = [
        {
          largeClass: 2, // 支付大类(固定值)
          groupId: 22, // 支付中类(固定值)
          paytypeId: 22, // 支付小类(固定值)
          amount: this.totalMoney, // 金额
          freightAmount: (this.orderData.freight / 100 || 0).toFixed(2), // 金额
          memberId: memberId, // 如果微信支付传memberId
          openId: wx.getStorageSync('openid'), // 微信openId
          appId: wx.getStorageSync('appid') // 微信appId
        }
      ];
      const pay_res = await orderPay(this.orderId, payParams);
      uni.hideLoading();
      if (pay_res.code !== 0) {
        uni.showModal({
          title: '提示',
          content: '调用支付失败',
          showCancel: false
        });
        return;
      }

      const doc = JSON.parse(pay_res.data.payInfo);
      const time = this.orderData.deliveryTime;
      this.$store.commit('join/SET_SCTIME', this.patientId);
      let params = {
        appId: doc.appId,
        nonceStr: doc.nonceStr,
        package: doc.package, // 固定值，以微信支付文档为主
        timeStamp: doc.timeStamp,
        paySign: doc.paySign,
        signType: doc.signType // 根据签名算法生成签名
      };
      uni.requestPayment({
        provider: 'wxpay',
        ...params,
        success: (win) => {
          uni.showToast({
            title: '支付成功，跳转中',
            icon: 'none',
            mask: true
          });
          setTimeout(() => {
            const params = `pages/registerResult/index?time=${time}&patientId=${self.patientId}&result=1`;
            uni.reLaunch({
              url: params
            });
          }, 1500);
        },
        fail: function (err) {
          const d1 = JSON.stringify(payParams);
          uni.showToast({
            title: '支付失败，跳转中',
            icon: 'none',
            mask: true
          });
          setTimeout(() => {
            const params = `pages/registerResult/index?time=${time}&patientId=${self.patientId}&result=0&orderId=${self.orderNo}&pay=${d1}`;
            uni.reLaunch({
              url: params
            });
          }, 1500);
        }
      });
    }
  }
};
</script>

<style lang="scss">
@mixin itemStyle {
  width: 700rpx;
  background: white;
  border-radius: 12rpx;
  margin: auto;
  margin-top: 24rpx;
  box-sizing: border-box;
  padding: 24rpx;
}
@mixin titleStyle {
  font-weight: bold;
  color: #222;
}
.detail {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  .address {
    @include itemStyle();
    display: flex;
    justify-content: space-between;
    .title {
      @include titleStyle();
      width: 360rpx;
    }
    .a-left {
      text-align: right;
    }
  }
  .time {
    @include itemStyle();
    .t-info {
      display: flex;
      justify-content: space-between;
      .t-title {
        @include titleStyle();
      }
    }
    .t-way {
      text-align: right;
    }
  }
  .order {
    @include itemStyle();
    .o-title {
      @include titleStyle();
      margin-bottom: 24rpx;
    }
    .drug-list {
      border-radius: 24rpx;
      background: #ffffff;
      display: flex;
      margin-bottom: 30rpx;
      .drug-img {
        width: 120rpx;
        height: 120rpx;
      }
      .drug-info {
        flex: 1;
        margin-left: 28rpx;
        font-size: 28rpx;
        color: rgba(0, 0, 0, 0.55);
        position: relative;
      }

      .title {
        max-height: 80rpx;
        font-size: 32rpx;
        line-height: 1.3em;
        color: rgba(0, 0, 0, 0.9);
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      .drug-num {
        display: flex;
        justify-content: space-between;
        font-size: 28rpx;
        color: rgba(0, 0, 0, 0.3);
        margin-top: 10rpx;
        overflow: hidden;
        align-items: flex-end;
      }
    }
    .drug-total {
      margin-top: 24rpx;
      text-align: right;
    }
  }
  .sys {
    @include itemStyle();
    margin-bottom: 50rpx;
    color: rgba(0, 0, 0, 0.55);
    .s-title {
      @include titleStyle();
      margin-bottom: 24rpx;
    }
    .s-item {
      display: flex;
      justify-content: space-between;
    }
  }
  .drug-payment {
    width: 150rpx;
    height: 66rpx;
    border: 1px solid #f34e1c;
    border-radius: 44rpx;
    color: #f34e1c;
    font-size: 32rpx;
    text-align: center;
    line-height: 66rpx;
    float: right;
    margin: 34rpx 0 10rpx;
  }
  .clearfix::after {
    content: ' ';
    display: block;
    clear: both;
    visibility: hidden;
    height: 0;
  }
}
</style>
